import { messages } from "share/common";
import configureStore from "stores";
import Selector from "components/selector";
import React from "react";
import { message, Select } from "antd";
import selectorData from "share/selectorData";
import Department from "components/template/department";
import moment from "moment";
import CostCenterSearchForm from "components/template/cost-center-search-form/cost-center-search-form";
import antdCommon from "share/prototype-extend/antd-common";
import openSlideFrame from "share/openSlideFrame";
import OperateReverseInvoice from "containers/corporate-payment-report/detail/pay-info-list/operate-reverse-invoice";
import PayWriteOffModal from "containers/corporate-payment-report/detail/pay-info-list/pay-write-off-modal";
import corporatePaymentReportService from "containers/corporate-payment-report/corporate-payment-report.service";
import WriteOffListModal from "containers/financial-management/corporate-payment-report-view/outstanding-business/write-off-list-modal";
import { openModalDirect } from "components/method/openModal";
const Option = Select.Option;
const { renderPopover } = antdCommon;

let getSearchForm = (env) => [
  {
    component: () => (
      <Selector
        allowClear={false}
        type={"setOfBooksByTenant"}
        params={{ roleType: "TENANT" }}
        entity
        onChange={env.handleChangeSetOfBook}
      />
    ),
    id: "setOfBooksId",
    judgeInTitle: true,
    label: messages("finance-4.key66") /*账套*/,
    initialValue: {
      setOfBooksName: configureStore.store.getState().login.company.setOfBooksName,
      id: configureStore.store.getState().login.company.setOfBooksId,
    },
    tagUnclosed: true,
    parser: (value) => ({ setOfBookId: value ? value.id : undefined }),
    tagParser: (value) => value.setOfBooksName,
  },
  {
    id: "docCompanyOID",
    label: messages("finance-9.key141") /*公司*/,
    component: "Chooser",
    props: {
      type: "available_company_setOfBooks",
      labelKey: "name",
      valueKey: "companyOID",
      single: true,
      listExtraParams: {
        enabled: true,
        setOfBooksId: configureStore.store.getState().login.company.setOfBooksId,
      },
    },
    initialValue: [
      {
        name: configureStore.store.getState().login.company.name,
        companyOID: configureStore.store.getState().login.company.companyOID,
      },
    ],
    parser: (value) => ({
      docCompanyOID: value && value.length ? value.map((item) => item.companyOID)[0] : null,
    }),
  },
  {
    id: "corpSupplierId",
    label: messages("finance-9.key1") /*供应商*/,
    component: "Chooser",
    props: {
      type: "vendor_account",
      labelKey: "venNickname",
      valueKey: "id",
      single: true,
      listExtraParams: {
        companyOid: configureStore.store.getState().login.company.companyOID,
      },
      dataIndex: "corpSupplierId",
    },
    parser: (value) => ({
      corpSupplierId: value ? value.map((item) => item.id)[0] : null,
    }),
  },
  {
    id: "paymentScheduleType",
    label: messages("finance-9.key142") /*业务类型*/,
    component: "Select",
    props: {
      placeholder: messages("basic-6.key27") /*请选择temp*/,
      style: { width: "100%" },
    },
    dataIndex: "paymentScheduleType",
    children: [
      { label: messages("finance-9.key46") /*到票支付*/, value: 1001 },
      { label: messages("finance-9.key163") /*无票预付*/, value: 1003 },
    ].map((item) => <Option key={item.value}>{item.label}</Option>),
    tagParser: (value) =>
      value === 1001 ? messages("finance-9.key46") /*到票支付*/ : messages("finance-9.key163") /*无票预付*/,
  },
  {
    id: "applicantOID",
    label: messages("expense-1.key618") /*申请人姓名/工号*/,
    component: "Selector",
    props: {
      placeholder: messages("expense-1.key619") /*请输入工号/姓名/手机号/部门/邮箱/职位*/,
      type: "user",
      selectorItem: {
        ...selectorData["user"],
        url: `/api/users/v3/search`,
        label: (record) =>
          `${record.employeeID}-${record.fullName}${
            record.status !== 1001
              ? `（${
                  record.status === 1002
                    ? messages("expense-1.key620") /*待离职员工*/
                    : messages("expense-1.key621") /*离职员工*/
                }）`
              : ""
          }`,
      },
      searchIfKeywordIsNull: false,
    },
  },
  {
    id: "formOIDs",
    component: "MultiSelectorV2",
    label: messages("expense-1.key617") /*表单类型*/,
    props: {
      type: "authority_form",
      params: { entityType: 3004 },
      labelKey: "formName",
      isShowSelectAll: true,
    },
    parser: (value) => ({
      formOIDs: value ? value.map((item) => item.formOID) : null,
    }),
  },
  {
    id: "departmentOIDs",
    label: messages("common.department") /*部门*/,
    component: <Department />,
    parser: (value) => ({
      departmentOIDs: value ? value.map((item) => item.departmentOID) : null,
    }),
    tagParser: (value) => value.map((item) => item.title).join(","),
  },
  {
    id: "currencyCode",
    label: messages("common.currency") /*币种*/,
    component: "Selector",
    props: {
      type: "currency",
      params: { userOId: configureStore.store.getState().login.loginUser.userOID },
      filter: (item) => item.enable,
      showSearch: true,
    },
  },
  {
    id: "submittedDate",
    label: messages("common.submit.date") /*提交日期*/,
    component: "DateRangePicker",
    parser: (value) => ({
      submitStartDate: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : null,
      submitEndDate: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : null,
    }),
  },
  {
    id: "approvalDate",
    label: messages("expense-1.key623") /*审批日期*/,
    component: "DateRangePicker",
    parser: (value) => ({
      approvalStartDate: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : null,
      approvalEndDate: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : null,
    }),
  },
  {
    id: "bookDate",
    label: messages("expense-1.key410") /*记账日期*/,
    component: "DateRangePicker",
    parser: (value) => ({
      bookStartDate: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : undefined,
      bookEndDate: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : undefined,
    }),
  },
  {
    id: "payDate",
    label: messages("expense-1.key611") /*付款日期*/,
    component: "DateRangePicker",
    parser: (value) => ({
      realPaymentStartDate: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : null,
      realPaymentEndDate: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : null,
    }),
  },
  {
    id: "financeApprovalOIDs",
    label: messages("expense-1.key630") /*审核通过人*/,
    component: "Chooser",
    props: {
      type: "finance-auditable-users",
      labelKey: "fullName",
      valueKey: "userOID",
    },
    parser: (value) => ({
      financeApprovalOIDs: value ? value.map((item) => item.userOID) : null,
    }),
    JSONObjectFormatterParams: ["fullName", "userOID"],
  },
  {
    id: "searchCostCenterCommands",
    label: messages("expense-1.key627") /*成本中心*/,
    component: <CostCenterSearchForm title={messages("expense-1.key627") /*成本中心*/} />,
    tagParser: (value) =>
      messages("common.total.selected", {
        arg1: value.length,
      }) /*已选 {arg1} 条*/,
  },
  {
    id: "contractHeaderId",
    label: messages("finance-9.key143") /*合同*/,
    component: "Chooser",
    props: {
      single: true,
      type: "contract_header",
      labelKey: "contractNumber",
      valueKey: "id",
      listExtraParams: {
        setOfBooksId: configureStore.store.getState().login.company.setOfBooksId,
      },
    },
    parser: (value) => ({
      contractHeaderId: value ? value.map((item) => item.id)[0] : null,
    }),
  },
  {
    id: "businessCode",
    label: messages("expense-1.key622") /*单据ID*/,
    component: "Input",
  },
];

let getColumns = (env) => [
  {
    title: messages("finance-9.key141") /*公司*/,
    dataIndex: "docCompanyName",
    width: 120,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("common.document.name") /*单据名称*/,
    dataIndex: "formName",
    width: 220,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("finance-9.key1") /*供应商*/,
    dataIndex: "corpSupplierName",
    width: 220,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("finance-9.key143") /*合同*/,
    dataIndex: "contractName",
    width: 220,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("common.applicant") /*申请人*/,
    dataIndex: "applicantName",
    width: 100,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("common.department") /*部门*/,
    dataIndex: "departmentName",
    width: 120,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("finance-9.key144") /*单据编号*/,
    dataIndex: "businessCode",
    width: 120,
    render: (value, record) => <a onClick={() => env.openReportDetail(record.entityOID)}>{value || "-"}</a>,
  },
  {
    title: messages("finance-9.key142") /*业务类型*/,
    dataIndex: "paymentScheduleTypeName",
    width: 80,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("finance-9.key43") /*费用/付款类型*/,
    dataIndex: "businessType",
    width: 120,
    render: (val) => renderPopover(val),
  },
  {
    title: messages("finance-9.key4") /*到票金额*/,
    dataIndex: "newInvoiceTotalAmount",
    align: "right",
    width: 120,
    render: (value) => (value !== null ? React.Component.prototype.filterMoney(value) : "-"),
  },
  {
    title: messages("finance-9.key111") /*已支付金额*/,
    dataIndex: "planedAmount",
    align: "right",
    width: 120,
    render: (value) => (value !== null ? React.Component.prototype.filterMoney(value) : "-"),
  },
  {
    title: messages("finance-9.key9") /*核销金额*/,
    dataIndex: "writeOffAmount",
    align: "right",
    width: 120,
    render: (value) => (value !== null ? React.Component.prototype.filterMoney(value) : "-"),
  },
  {
    title: messages("finance-9.key145") /*红冲金额*/,
    dataIndex: "reverseInvoiceAmount",
    align: "right",
    width: 120,
    render: (value) => (value !== null ? React.Component.prototype.filterMoney(value) : "-"),
  },
  {
    title: messages("finance-9.key146") /*记账日期*/,
    dataIndex: "bookDate",
    width: 160,
    render: (value) => (value ? moment(value).format("YYYY-MM-DD") : "-"),
  },
  {
    title: messages("finance-9.key121") /*预计到票日期*/,
    dataIndex: "estimatedInvoiceDate",
    width: 160,
    render: (value) => (value ? moment(value).format("YYYY-MM-DD") : "-"),
  },
  {
    title: messages("finance-9.key147") /*余额*/,
    dataIndex: "balance",
    align: "right",
    width: 160,
    render: (value) => (value !== null ? React.Component.prototype.filterMoney(value) : "-"),
  },
  {
    title: messages("common.operation") /*操作*/,
    dataIndex: "operation",
    width: 110,
    render: (value, record) => env.renderOperationColumn(value, record),
  },
];

const DataHOC = (WrappedComponent) => {
  class Hoc extends React.Component {
    state = {
      loading: false,
      searchForm: getSearchForm(this),
      columns: getColumns(this),
    };

    handleChangeSetOfBook = (value) => {
      const { searchForm } = this.state;
      let setOfBooksId = this.safeGet(
        searchForm.find((item) => item.id === "docCompanyOID") || {},
        "props.listExtraParams.setOfBooksId"
      );
      if (setOfBooksId !== value.id) {
        this.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
          docCompanyOID: null,
          contractHeaderId: null,
        });
        searchForm.map((item) => {
          if (item.id === "docCompanyOID") {
            item.props.listExtraParams = {
              setOfBooksId: value.id,
              enabled: true,
            };
          }
          if (item.id === "contractHeaderId") {
            item.props.listExtraParams = {
              setOfBooksId: value.id,
            };
          }
        });
        this.setState({ searchForm });
      }
    };

    openReportDetail = (entityOID) => {
      entityOID &&
        openSlideFrame.openCorporateReportDetail(
          {
            expenseReportOID: entityOID,
            entry: "view",
            readOnly: true,
          },
          {
            noPadding: true,
          },
          this
        );
    };

    handleAddWriteOff = (record) => {
      PayWriteOffModal.open(this, {
        payInfoDetail: {
          invoiceViewDTO: { expenseTypeOID: record.expenseTypeOID },
        },
        expenseInfo: {
          docCompanyOID: record.docCompanyOID,
          corpSupplierId: record.corpSupplierId,
          currencyCode: record.currencyCode,
          setOfBooksId: record.setOfBooksId,
          expenseReportOID: record.entityOID,
        },
      }).then(({ data, closeModal, context }) => {
        corporatePaymentReportService
          .addWriteOff(record.id, data)
          .then(() => {
            context.setState({ loading: false });
            message.success(messages("common.operate.success") /*操作成功*/);
            closeModal();
            this.advancedTableRef.getList();
          })
          .catch((e) => {
            message.error(e.response.data.message);
            context.setState({ loading: false });
          });
      });
    };

    viewWriteOffList = (paymentScheduleId) => {
      openModalDirect(WriteOffListModal, { paymentScheduleId }, this);
    };

    renderOperationColumn = (value = "", record) => {
      return record.balance && record.balance > 0 ? (
        <span>
          {this.safeGet(record, "writeOffInfo.writeOffEnabled") && (
            <div>
              <a onClick={(e) => this.handleAddWriteOff(record)}>{messages("finance-9.key65") /*添加核销*/}</a>
            </div>
          )}
          {this.safeGet(record, "writeOffInfo.writeOffAvailable") && (
            <div>
              <a onClick={() => this.viewWriteOffList(record.paymentScheduleId)}>
                {messages("finance-9.key148") /*核销记录*/}
              </a>
            </div>
          )}
          <OperateReverseInvoice
            info={Object.assign({}, record, {
              invoiceViewDTO: { amount: record.newInvoiceTotalAmount },
              planedAndAssociateAmount: record.planedAmount,
              writeOffAmount: record.writeOffAmount,
              reversedAmount: record.reverseInvoiceAmount,
              availableAmount: record.balance,
              id: record.paymentScheduleId,
            })}
            onRefresh={this.advancedTableRef.getList}
          />
        </span>
      ) : (
        "-"
      );
    };

    render() {
      const { searchForm, columns, loading } = this.state;
      return (
        <WrappedComponent
          loading={loading}
          onRef={(ref) => (this.advancedTableRef = ref.advancedTableRef)}
          searchForm={searchForm}
          columns={columns}
        />
      );
    }
  }
  return Hoc;
};

export default DataHOC;
